
$(function() {
	Meeting_Record_Add.init();
})

var Meeting_Record_Add={
	/**
	 * 用户数据集
	 */
	userData:[],
	/**
	 * 下拉多选
	 */
	mySelectCheck:null,
	/**
	 * 单选
	 */
	mySelectRadio:null,
	
	fileArrayPlan:[],
	textArrayPlan : [],
	fileSplitSize :1024 * 1024 * 10,// 文件分割上传的间隙大小 10M
	
	init:function(){
		Meeting_Record_Add.loadUseData();
		Meeting_Record_Add.initMySelect();
		Meeting_Record_Add.initDatePicker();
		Meeting_Record_Add.initFileUpload();
	},
	/**
	 * 日期初始化
	 */
	initDatePicker:function(){
		laydate.render({
			elem: '#meetTime'
		});
	},
	/**
	 * 加载可用用户
	 * 1、可以，0、不可用
	 */
	loadUseData:function(){
		$.ajax({
			url : "/crm/user/loadUserByIsUse", // 请求的url地址
			dataType : "json", // 返回格式为json
			async : false,// 请求是否异步，默认为异步，这也是ajax重要特性
			data : {
				isUse:1
			}, // 参数值
			type : "post", // 请求方式
			success : function(data) {
				Meeting_Record_Add.userData = data;
			},
			error : function() {
			}
		})
	},
	initMySelect:function(){
		var mySelect= $("#mySelect").mySelect({
			  mult:true,//true为多选,false为单选
			  option:Meeting_Record_Add.userData,
			  onChange:function(res){//选择框值变化返回结果
				//console.log(res)
				 //console.log(mySelect.getResultDatas());
			  }
		  });
		Meeting_Record_Add.mySelectCheck = mySelect;
		
		var mySelect2= $("#mySelect2").mySelect({
			  mult:false,//true为多选,false为单选
			  option:Meeting_Record_Add.userData,
			  onChange:function(res){//选择框值变化返回结果
				//console.log(res)
				 //console.log(mySelect.getResultDatas());
			  }
		  });
		Meeting_Record_Add.mySelectRadio = mySelect2;
	},
	
	/**
	 * 初始化上传
	 */
	initFileUpload:function() {
		//上传方案初始化
		$("#UploadPlanFile").on("change", function() {
			var files = this.files;
			var files = this.files;
			if((Meeting_Record_Add.fileArrayPlan.length+files.length)>4){
				layer.alert("选择的文件数量大于四个，请重新选择！");
				return;
			}
			$.each(files, function(key, val) {
				var file = val;
				var name = file.name;
				var size = file.size, type = file.type || "", id =(file.lastModified + "").replace(/\W/g, '') + size + type.replace(/\W/g, '') + name.replace(/\W/g, '');
				if (!limitFileType(name)) {// 文件内容为空
					layer.alert("不接受此文件类型！");
					return;
				}else if (size==0) {// 文件内容为空
					layer.alert("文件内容不存在！");
					return;
				}else if (size > 1024 * 1024 * 1024 * 2) {// 大于2G
					layer.alert("文件过大！");
					return;
				} else if (Meeting_Record_Add.fileArrayPlan.indexOf(id) != -1) {
					layer.alert("文件已存在！");
					return;
				} else {
					Meeting_Record_Add.fileArrayPlan.push(id);
					Meeting_Record_Add.fileArrayPlan[id] = file;
//					Meeting_Record_Add.textArrayPlan.push(id);
//					var obj={};
//					obj.name=name;
//					Meeting_Record_Add.textArrayPlan[id] = obj;
				}
				// 文件添加显示
				var item = $('<li class="file_item filen" fileId=' + id + '>' + '<span>'+name+'</span><img class="ed_sel_del" src="../../image/close.png" />' + '</li>');
				$("#UploadPlanFile").parents(".up_adimg_bg").after(item);
			});
			Meeting_Record_Add.limitBehaviour();
		})
		// 删除文件
		$("#uploadPlan").on("click", ".ed_sel_del", function() {
			var deleteDom = $(this).parents(".filen");
			layer.confirm('确定要删除文件吗?',{btn: ['确定', '取消'],title:"提示"},function(index) {
				if (deleteDom) {
					layer.close(index);
					var fileId = deleteDom.attr('fileId');
					Meeting_Record_Add.fileArrayPlan.splice(Meeting_Record_Add.fileArrayPlan.indexOf(fileId), 1);
					//Meeting_Record_Add.textArrayPlan.splice(Meeting_Record_Add.textArrayPlan.indexOf(fileId), 1);
					deleteDom.remove();
					deleteDom = null;
					Meeting_Record_Add.limitBehaviour();
				}
			});
		});
	},
	/**
	 * 限制文件数量为4
	 */
	limitBehaviour:function() {
		var items = $("#uploadPlan").children(".file_item");
		if (items.length >= 4) {
			$("#uploadPlan .up_adimg_bg").hide();
		} else {
			$("#uploadPlan .up_adimg_bg").show();
		}
		$.each(items, function(k, v) {
			if (k > 3)
				$(this).remove();
		})
		
	},
	
	/**
	 * 编辑保存
	 */
	eaitSave:function(){
		var obj ={};
		var meetTitle = $("#meetTitle").val();
		if(isBlank(meetTitle)){
			layer.msg("会议标题未填写！");
			return false;
		}
		var meetSpeaker = "";
		$.each(Meeting_Record_Add.mySelectRadio.getResultDatas(), function(k, v) {
			meetSpeaker += ','+v.name;
		})
		meetSpeaker = meetSpeaker.substring(1);
		if(isBlank(meetSpeaker)){
			layer.msg("会议主讲者未选择！");
			return false;
		}
		var joinUserUuids ="";
		var joinUserNames = "";
		$.each(Meeting_Record_Add.mySelectCheck.getResultDatas(), function(k, v) {
			joinUserUuids += ','+v.value;
			joinUserNames += ','+v.name;
		})
		joinUserUuids = joinUserUuids.substring(1);
		joinUserNames = joinUserNames.substring(1);
		if(isBlank(joinUserUuids)){
			layer.msg("会议参加者未选择！");
			return false;
		}
		var meetTime = $("#meetTime").val();
		if(isBlank(meetTime)){
			layer.msg("会议时间未选择！");
			return false;
		}
		var meetContent = $("#meetContent").val();
		obj.meetTitle = meetTitle;
		obj.meetTime = meetTime;
		obj.meetContent = meetContent;
		obj.meetSpeaker = meetSpeaker;
		obj.joinUserUuids = joinUserUuids;
		obj.joinUserNames = joinUserNames;

		var title ="编辑确认";
		var content = '<div style="padding: 20px 80px 20px;">编辑保存成功后，用户信息会发生改变，请确认操作？</div>';
		AlertBox.confirm(content, title, Meeting_Record_Add.sureEdit, obj);
		
	},
	
	sureEdit:function(obj){
		var loading = layer.load(0, { //icon支持传入0-2
		    shade: [0.5, 'gray'], //0.5透明度的灰色背景
		    content: '文件上传中',
		    success: function (layero) {
		        layero.find('.layui-layer-content').css({
		            'padding-top': '39px',
		            'width': '80px'
		        });
		    }
		});
		var uploadPath="meeting//"+obj.meetTitle;
		//上传文件
		funFileUpload(Meeting_Record_Add.fileArrayPlan[0],Meeting_Record_Add.fileArrayPlan,uploadPath);
		layer.close(loading);
		obj.meetFilePath = JSON.stringify(Meeting_Record_Add.textArrayPlan);
		console.log(obj);
		$.ajax({
			url : "/crm/meetingRecord/save",
			dataType : "json",
			async : false,
			data : obj,
			type : "post",
			success : function(data) {
				
				if (data.status) {
					Meeting_Record_Add.allClear();
				} 
				AlertBox.alert(data.info, "");
			},
			error : function() {

			}
		});
	},
	allClear:function(){
		Meeting_Record_Add.textArrayPlan = [];
		Meeting_Record_Add.fileArrayPlan=[];
		$.each($("#uploadPlan").children(".file_item"), function() {
			$(this).remove();
		});
		$("#meetTitle").val("");
		$("#meetTime").val("");
		$("#meetContent").val("");
		$(".img_sel2").html('<div id="mySelect2" class="mySelect" ></div>');
		$(".img_sel").html('<div id="mySelect" class="mySelect" ></div>');
		Meeting_Record_Add.initMySelect();
	}
}

/**
 * 单文件上传
 */
var funFileUpload = function(fileid,fileArray,uploadPath,onsuccess, onerror, onpause) {
	var file = fileArray[fileid], now = performance.now();
	if (!fileid || !file)
		return;
	onsuccess = onsuccess || function() {
		funFileUpload(fileArray[0],fileArray,uploadPath);
	};

	onerror = onerror || function() {
		funFileUpload(fileArray[fileArray.indexOf(fileid) + 1],fileArray,uploadPath);
	};
	onpause = onpause || function() {
		funFileUpload(fileArray[fileArray.indexOf(fileid) + 1],fileArray,uploadPath);
	};
	if (file.flagPause == true) {
		onpause.call(fileid);
		return;
	}
	// objStateElement.wait(fileid);
	// 文件分割上传
	// 文件大小和分割起点
	// 注释的是本地存储实现
	var size = file.size, start = localStorage[fileid] * 1 || 0;
	// start = $("filelist_" + fileid).filesize;
	if (size == start) {
		// 已经传过了
		fileArray.shift();
		if (delete fileArray[fileid])
		// objStateElement.success(fileid, now);
		// 回调
		onsuccess.call(fileid, {});
		localStorage.clear();
		return;
	}

	var funFileSize = function() {
		if (file.flagPause == true) {
			onpause.call(fileid);
			return;
		}
		var data = new FormData();
		var name = file.name.replace(/[\@\#\$\%\^\&\*\{\}\:\"\L\<\>\?\ ]/g ,'');
		data.append("fileName", encodeURIComponent(name));
		data.append("fileid", fileid);
		data.append("myFile", file.slice(start, start + Meeting_Record_Add.fileSplitSize));
		data.append("start", start + "");
		data.append("flag",(start + Meeting_Record_Add.fileSplitSize)>=size?"COMPLETE":"UPLOAD");
		data.append("uploadPath",uploadPath);
		var p = "?name=" + encodeURIComponent(file.name) + "&fileid" + fileid + "&start" + start;
		// XMLHttpRequest 2.0 请求
		var xhr = new XMLHttpRequest();
		xhr.open("post", "/crm/fileUpload", false);
		// .setRequestHeader("X_Requested_With",
		// location.href.split("/")[5].replace(/[^a-z]+/g,"$"));
		// xhr.setRequestHeader("Content-type", "multipart/form-data");
		// 上传进度中
		xhr.upload.addEventListener("progress", function(e) {
			// objStateElement.backgroundSize(fileid, (e.loaded + start) / size
			// * 100);
		}, false);
		// ajax成功后
		xhr.onreadystatechange = function(e) {
			if (xhr.readyState == 4) {
				if (xhr.status == 200) {
					try {
						var json = JSON.parse(xhr.responseText);
						temp = 2;
					} catch (e) {
						// objStateElement.error(fileid);
						return;
					}
					// var json = JSON.parse(xhr.responseText);
					if (!json || !json.succ) {
						// objStateElement.error(fileid);
						onerror.call(fileid, json);
						return;
					}

					if (start + Meeting_Record_Add.fileSplitSize >= size) {
						// 超出，说明全部分割上传完毕
						// 上传队列中清除者一项
						fileArray.shift();
						if (delete fileArray[fileid])
						// objStateElement.success(fileid, now);
						// 回调
						onsuccess.call(fileid, json);
						filePath = json.data.savePath;
						var obj ={};
						obj.name = name;
						obj.filePath = filePath
						Meeting_Record_Add.textArrayPlan.push(obj);
						
						localStorage.clear();
					} else {
						// 尚未完全上传完毕
						// 改变下一部分文件的起点位置
						start += Meeting_Record_Add.fileSplitSize;
						// 存储上传成功的文件点，以便出现意外的时候，下次可以断点续传
						localStorage.setItem(fileid, start + "");
						// 上传下一个分割文件
						funFileSize();

					}
				} else {
					// objStateElement.error(fileid);
				}
			}
		};

		xhr.send(data);
	};
	// 文件分割上传开始
	funFileSize();
};